/**
 * 赛博侦探游戏 - 主游戏入口
 * 初始化Phaser游戏引擎，配置场景和基本设置
 */

import Phaser from 'phaser';
import { MainMenuScene } from './scenes/MainMenuScene';
import { InvestigationScene } from './scenes/InvestigationScene';

/**
 * 游戏配置接口
 */
interface GameConfig extends Phaser.Types.Core.GameConfig {
  parent: string | HTMLElement;
}

/**
 * 赛博侦探游戏类
 */
export class CyberDetectiveGame {
  private game: Phaser.Game | null = null;
  private config: GameConfig;

  constructor(containerId: string) {
    this.config = this.createGameConfig(containerId);
  }

  /**
   * 创建游戏配置
   */
  private createGameConfig(containerId: string): GameConfig {
    return {
      type: Phaser.AUTO,
      width: 1200,
      height: 800,
      parent: containerId,
      backgroundColor: '#0a0a0a',
      scale: {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        min: {
          width: 800,
          height: 600
        },
        max: {
          width: 1920,
          height: 1080
        }
      },
      physics: {
        default: 'arcade',
        arcade: {
          gravity: { x: 0, y: 0 },
          debug: false
        }
      },
      dom: {
        createContainer: true
      },
      scene: [
        MainMenuScene,
        InvestigationScene
      ],
      audio: {
        disableWebAudio: false
      },
      render: {
        antialias: true,
        pixelArt: false,
        roundPixels: false
      },
      fps: {
        target: 60,
        forceSetTimeOut: true
      },
      loader: {
        baseURL: '',
        crossOrigin: 'anonymous'
      }
    };
  }

  /**
   * 启动游戏
   */
  public start(): void {
    if (this.game) {
      console.warn('游戏已经启动');
      return;
    }

    try {
      this.game = new Phaser.Game(this.config);
      
      // 游戏启动事件监听
      this.game.events.on('ready', () => {
        console.log('赛博侦探游戏启动成功');
        this.onGameReady();
      });

      // 游戏暂停/恢复事件
      this.game.events.on('pause', () => {
        console.log('游戏暂停');
      });

      this.game.events.on('resume', () => {
        console.log('游戏恢复');
      });

      // 错误处理
      this.game.events.on('error', (error: Error) => {
        console.error('游戏错误:', error);
        this.handleGameError(error);
      });

    } catch (error) {
      console.error('游戏启动失败:', error);
      this.handleGameError(error as Error);
    }
  }

  /**
   * 游戏准备就绪回调
   */
  private onGameReady(): void {
    // 设置全局游戏配置
    if (this.game) {
      // 禁用右键菜单
      this.game.canvas.oncontextmenu = (e) => {
        e.preventDefault();
      };

      // 设置游戏焦点
      this.game.canvas.focus();

      // 添加窗口大小变化监听
      window.addEventListener('resize', () => {
        this.handleResize();
      });

      // 添加可见性变化监听
      document.addEventListener('visibilitychange', () => {
        this.handleVisibilityChange();
      });
    }
  }

  /**
   * 处理窗口大小变化
   */
  private handleResize(): void {
    if (this.game && this.game.scale) {
      // Phaser会自动处理缩放，这里可以添加额外的逻辑
      console.log('窗口大小变化，游戏自动调整');
    }
  }

  /**
   * 处理页面可见性变化
   */
  private handleVisibilityChange(): void {
    if (!this.game) return;

    if (document.hidden) {
      // 页面隐藏时暂停游戏
      this.pause();
    } else {
      // 页面显示时恢复游戏
      this.resume();
    }
  }

  /**
   * 暂停游戏
   */
  public pause(): void {
    if (this.game && !this.game.isPaused) {
      this.game.pause();
    }
  }

  /**
   * 恢复游戏
   */
  public resume(): void {
    if (this.game && this.game.isPaused) {
      this.game.resume();
    }
  }

  /**
   * 停止游戏
   */
  public stop(): void {
    if (this.game) {
      this.game.destroy(true);
      this.game = null;
      console.log('游戏已停止');
    }
  }

  /**
   * 重启游戏
   */
  public restart(): void {
    this.stop();
    setTimeout(() => {
      this.start();
    }, 100);
  }

  /**
   * 获取游戏实例
   */
  public getGame(): Phaser.Game | null {
    return this.game;
  }

  /**
   * 获取当前场景
   */
  public getCurrentScene(): Phaser.Scene | null {
    if (!this.game || !this.game.scene) return null;
    
    const activeScenes = this.game.scene.getScenes(true);
    return activeScenes.length > 0 ? activeScenes[0] : null;
  }

  /**
   * 切换到指定场景
   */
  public switchToScene(sceneKey: string, data?: any): void {
    if (!this.game || !this.game.scene) {
      console.warn('游戏未初始化，无法切换场景');
      return;
    }

    try {
      this.game.scene.start(sceneKey, data);
    } catch (error) {
      console.error('场景切换失败:', error);
    }
  }

  /**
   * 处理游戏错误
   */
  private handleGameError(error: Error): void {
    console.error('游戏运行错误:', {
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    });

    // 可以在这里添加错误上报逻辑
    // 或者显示用户友好的错误信息
  }

  /**
   * 获取游戏统计信息
   */
  public getGameStats(): any {
    if (!this.game) return null;

    return {
      isRunning: !this.game.isPaused,
      fps: this.game.loop.actualFps,
      width: this.game.scale.width,
      height: this.game.scale.height,
      renderer: this.game.renderer.type === Phaser.WEBGL ? 'WebGL' : 'Canvas',
      scenes: this.game.scene.scenes.map(scene => ({
        key: scene.scene.key,
        active: scene.scene.isActive(),
        visible: scene.scene.isVisible()
      }))
    };
  }

  /**
   * 设置游戏音量
   */
  public setVolume(volume: number): void {
    if (!this.game || !this.game.sound) return;

    // 确保音量在0-1范围内
    const clampedVolume = Math.max(0, Math.min(1, volume));
    this.game.sound.volume = clampedVolume;
  }

  /**
   * 静音/取消静音
   */
  public toggleMute(): void {
    if (!this.game || !this.game.sound) return;

    this.game.sound.mute = !this.game.sound.mute;
  }

  /**
   * 获取游戏是否静音
   */
  public isMuted(): boolean {
    return this.game?.sound?.mute || false;
  }

  /**
   * 截图功能
   */
  public takeScreenshot(callback?: (dataURL: string) => void): void {
    if (!this.game || !this.game.renderer) {
      console.warn('无法截图：游戏未初始化');
      return;
    }

    try {
      this.game.renderer.snapshot((image: HTMLImageElement) => {
        if (callback) {
          callback(image.src);
        } else {
          // 默认下载截图
          const link = document.createElement('a');
          link.download = `cyber-detective-${Date.now()}.png`;
          link.href = image.src;
          link.click();
        }
      });
    } catch (error) {
      console.error('截图失败:', error);
    }
  }

  /**
   * 检查游戏是否支持WebGL
   */
  public static isWebGLSupported(): boolean {
    try {
      const canvas = document.createElement('canvas');
      const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
      return !!gl;
    } catch (error) {
      return false;
    }
  }

  /**
   * 获取设备信息
   */
  public static getDeviceInfo(): any {
    return {
      userAgent: navigator.userAgent,
      platform: navigator.platform,
      language: navigator.language,
      cookieEnabled: navigator.cookieEnabled,
      onLine: navigator.onLine,
      screenWidth: screen.width,
      screenHeight: screen.height,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      pixelRatio: window.devicePixelRatio || 1,
      webglSupported: CyberDetectiveGame.isWebGLSupported()
    };
  }
}

/**
 * 游戏工厂函数
 * 创建并返回游戏实例
 */
export function createGame(containerId: string): CyberDetectiveGame {
  return new CyberDetectiveGame(containerId);
}

/**
 * 默认导出游戏类
 */
export default CyberDetectiveGame;